package com.gao.weblog.admin.config;

import com.gao.weblog.jwt.config.JwtAuthenticationSecurityConfig;
import com.gao.weblog.jwt.filter.TokenAuthenticationFilter;
import com.gao.weblog.jwt.handler.RestAccessDeniedHandler;
import com.gao.weblog.jwt.handler.RestAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationSecurityConfig jwtAuthenticationSecurityConfig;
    @Autowired
    private RestAuthenticationEntryPoint authenEntryPoint;
    @Autowired
    private RestAccessDeniedHandler deniedHandler;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin().disable()
                .apply(jwtAuthenticationSecurityConfig)
            .and()
                .authorizeRequests()
                .mvcMatchers("/admin/**").authenticated()
                .anyRequest().permitAll()
            .and()
                .httpBasic().authenticationEntryPoint(authenEntryPoint)
            .and()
                .exceptionHandling().accessDeniedHandler(deniedHandler)
            .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
                .addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public TokenAuthenticationFilter tokenAuthenticationFilter(){
        return  new TokenAuthenticationFilter();
    }
}
